<template>
    <view class="container">
        <u-toast ref="notify"></u-toast>
        <view class="left-bottom-sign"></view>
        <view class="back-btn yticon icon-zuojiantou-up" @click="pageBack"></view>
        <view class="right-top-sign"></view>
        <!-- 设置白色背景防止软键盘把下部绝对定位元素顶上来盖住输入框等 -->
        <view class="wrapper">
            <view class="left-top-sign">REGISTER</view>
            <view class="welcome">
                注册！
            </view>
            <!-- 步骤 1: 选择角色 -->
            <view v-if="currentStep === 1" class="w-full px-30">
                <text class="text-bold text-130">选择角色</text>
                <view class="roleBtns" ref="roleBtns">
                    <u-button v-for="(role, index) in roleRange" type="primary" :class="roleBtn" :plain="true"
                        :text="role.name" size="large" @click="onRoleChange(role.id)"></u-button>
                </view>
                <button @click="pageBack"
                    class="w-full h-46 f-c-c b-radius-sm bg-gray-500 color-FFFFFF text-110 mt-20 back">
                    返回
                </button>
            </view>

            <!-- 步骤 2: 填写基础信息 -->
            <view v-if="currentStep === 2" class="w-full px-30">
                <text class="text-bold text-130">填写基础信息</text>
                <view class="input-content">
                    <view class="input-item">
                        <text class="tit">真实姓名</text>
                        <input type="text" v-model="registerParams.userName" placeholder="请输入真实姓名" maxlength="20" />
                    </view>
                    <view class="input-item">
                        <text class="tit">身份证号</text>
                        <input type="text" v-model="registerParams.idNumber" placeholder="请输入身份证号" maxlength="20" />
                    </view>
                    <view class="input-item" style="height: 105px;">
                        <text class="tit">性别</text>
                        <view class="gender-buttons">
                            <button :class="{'gender-button': true, 'active': registerParams.gender == 1}"
                                @click="selectGender('1')">
                                男
                            </button>
                            <button :class="{'gender-button': true, 'active': registerParams.gender == 2}"
                                @click="selectGender('2')">
                                女
                            </button>
                        </view>
                    </view>
                    <view class="input-item">
                        <text class="tit">电话</text>
                        <input type="text" v-model="registerParams.phone" placeholder="请输入电话号码" maxlength="11" />
                    </view>
                </view>
                <button @click="prevStep"
                    class="w-full h-46 f-c-c b-radius-sm bg-gray-500 color-FFFFFF text-110 mt-20 back">
                    上一步
                </button>
                <button ref='nextBtn2' @click="nextStep"
                    class="w-full h-46 f-c-c b-radius-sm color-FFFFFF text-110 mt-20 next">
                    下一步
                </button>
            </view>

            <!-- 步骤 3: 填写基础信息 -->
            <view v-if="currentStep === 3" class="w-full px-30">
                <text class="text-bold text-130">填写基础信息</text>
                <view class="input-content">
                    <view class="input-item" style="height: 220rpx;">
                        <text class="tit">头像</text>
                        <button class="avaterBtn" type="balanced" open-type="chooseAvatar"
                            @chooseavatar="onChooseavatar">
                            <u-avatar shape="square" size="75" :src="registerParams.icon"></u-avatar>
                        </button>
                    </view>

                    <view class="input-item">
                        <text class="tit">昵称</text>
                        <view class='input'>
                            <input type='nickname' name='nickname' v-model='registerParams.nickName'
                                placeholder="请输入昵称">
                            </input>
                        </view>

                    </view>
                </view>
                <button @click="prevStep"
                    class="w-full h-46 f-c-c b-radius-sm bg-gray-500 color-FFFFFF text-110 mt-20 back">
                    上一步
                </button>
                <button ref='nextBtn3' @click="nextStep"
                    class="w-full h-46 f-c-c b-radius-sm color-FFFFFF text-110 mt-20 next">
                    下一步
                </button>
            </view>

            <!-- 步骤 4: 其他信息 -->
            <view v-if="currentStep === 4" class="w-full px-30">
                <text class="text-bold text-130">其他信息</text>
                <!-- 根据角色选择显示额外信息 -->
                <view class="input-content">
                    <view v-if="registerParams.roleId === '10'">
                        <view class="input-item">
                            <text class="tit">商家名称</text>
                            <input type="text" v-model="registerParams.shopInfo.shopName" placeholder="商家名称" />
                        </view>

                        <view class="input-item-row">
                            <view class="input-item-2">
                                <text class="tit">区号</text>
                                <input type="text" v-model="registerParams.shopInfo.areaNum" placeholder="区号" />
                            </view>
                            <view class="input-item-2">
                                <text class="tit">门牌号</text>
                                <input type="text" v-model="registerParams.shopInfo.stallNum" placeholder="门牌号" />
                            </view>

                        </view>

                        <view class="input-item">
                            <text class="tit">店长名</text>
                            <input type="text" v-model="registerParams.shopInfo.shopOwner" placeholder="店长名" />
                        </view>

                        <view class="input-item">
                            <text class="tit">联系电话</text>
                            <input type="text" v-model="registerParams.shopInfo.shopPhone" placeholder="联系电话" />
                        </view>

                    </view>
                    <view v-else-if="registerParams.roleId === '8' || registerParams.roleId === '9'">
                        <view class="input-item" style="height: 300px; justify-content: flex-start; overflow: scroll;">
                            <text class="tit" style="margin-top: 17px;">选择分组</text>
                            <view class="group-buttons">
                                <button v-for="(group, index) in allGroup"
                                    :class="{'group-button': true, 'active': registerParams.groupId == group.groupId}"
                                    @click="selectGroup(group.groupId)">
                                    <text>{{group.groupName}}</text>
                                    <text>组长：{{ group.groupLeader }}</text>

                                </button>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="mt-30 w-full">
                    <!-- 协议 -->
                    <checkbox-group @change="
                            (e) => {
                                agreement = e.detail.value.includes('agreement');
                            }
                        " class="f-c-c">
                        <checkbox value="agreement" :checked="agreement" />
                        <view class="text-80">
                            已阅读并同意
                            <text style="color: #ff7391;">《商户服务及用户隐私协议》</text>
                        </view>
                    </checkbox-group>
                </view>
                <button @click="prevStep"
                    class="w-full h-46 f-c-c b-radius-sm bg-gray-500 color-FFFFFF text-110 mt-20 back">
                    上一步
                </button>
                <button ref='nextBtn4' @click="nextStep"
                    class="w-full h-46 f-c-c b-radius-sm color-FFFFFF text-110 mt-20 next">
                    注册
                </button>
            </view>
        </view>
    </view>
</template>


<script>
    import {
        authApi,
        groupApi,
        imageApi
    } from "@/api";

    export default {
        data() {
            return {
                currentStep: 1, // 当前步骤
                wxInfo: null,
                allGroup: [{
                        "groupId": "grp001",
                        "groupName": "甲组",
                        "groupStatus": 1,
                        "groupLeaderId": "usr101",
                        "groupLeader": "张三",
                        "groupNote": "主要研究团队",
                        "memberIds": [
                            "usr102",
                            "usr103",
                            "usr104"
                        ],
                        "memberNames": [
                            "李四",
                            "王五",
                            "赵六"
                        ]
                    },
                    {
                        "groupId": "grp002",
                        "groupName": "乙组",
                        "groupStatus": 0,
                        "groupLeaderId": "usr105",
                        "groupLeader": "李梅",
                        "groupNote": "数据分析小组",
                        "memberIds": [
                            "usr106",
                            "usr107"
                        ],
                        "memberNames": [
                            "陈涛",
                            "刘云"
                        ]
                    },
                    {
                        "groupId": "grp003",
                        "groupName": "丙组",
                        "groupStatus": 1,
                        "groupLeaderId": "usr108",
                        "groupLeader": "王强",
                        "groupNote": "开发团队",
                        "memberIds": [
                            "usr109",
                            "usr110",
                            "usr111",
                            "usr112"
                        ],
                        "memberNames": [
                            "吴丽",
                            "杨健",
                            "赵霞",
                            "孙红"
                        ]
                    },
                    {
                        "groupId": "grp004",
                        "groupName": "丁组",
                        "groupStatus": 1,
                        "groupLeaderId": "usr101",
                        "groupLeader": "张三",
                        "groupNote": "主要研究团队",
                        "memberIds": [
                            "usr102",
                            "usr103",
                            "usr104"
                        ],
                        "memberNames": [
                            "李四",
                            "王五",
                            "赵六"
                        ]
                    },
                    {
                        "groupId": "grp005",
                        "groupName": "5组",
                        "groupStatus": 1,
                        "groupLeaderId": "usr101",
                        "groupLeader": "张三",
                        "groupNote": "主要研究团队",
                        "memberIds": [
                            "usr102",
                            "usr103",
                            "usr104"
                        ],
                        "memberNames": [
                            "李四",
                            "王五",
                            "赵六"
                        ]
                    },
                    {
                        "groupId": "grp006",
                        "groupName": "6组",
                        "groupStatus": 1,
                        "groupLeaderId": "usr101",
                        "groupLeader": "张三",
                        "groupNote": "主要研究团队",
                        "memberIds": [
                            "usr102",
                            "usr103",
                            "usr104"
                        ],
                        "memberNames": [
                            "李四",
                            "王五",
                            "赵六"
                        ]
                    },
                    {
                        "groupId": "grp007",
                        "groupName": "7组",
                        "groupStatus": 1,
                        "groupLeaderId": "usr101",
                        "groupLeader": "张三",
                        "groupNote": "主要研究团队",
                        "memberIds": [
                            "usr102",
                            "usr103",
                            "usr104"
                        ],
                        "memberNames": [
                            "李四",
                            "王五",
                            "赵六"
                        ]
                    },
                    {
                        "groupId": "grp008",
                        "groupName": "8组",
                        "groupStatus": 1,
                        "groupLeaderId": "usr101",
                        "groupLeader": "张三",
                        "groupNote": "主要研究团队",
                        "memberIds": [
                            "usr102",
                            "usr103",
                            "usr104"
                        ],
                        "memberNames": [
                            "李四",
                            "王五",
                            "赵六"
                        ]
                    },
                ],
                agreement: false,
                passwordRepeat: "",
                registerParams: {
                    wxCode: 0,
                    roleId: "0", // 角色id
                    shopId: null, // 商家用户id
                    groupId: null, // 小组id
                    nickName: "微信用户", // 昵称
                    userName: "", // 真实姓名
                    password: "888888", // 默认密码
                    phone: "", // 电话号码
                    icon: "", // 用户头像
                    gender: 0, // 性别
                    idNumber: null,
                    shopInfo: { // 商家信息
                        shopSn: null, // 商户id
                        shopName: null, // 商家名称
                        shopSn: "", // 商家编号
                        areaNum: null, // 区号
                        stallNum: null, // 门牌号
                        shopOwner: null, // 店长名
                        shopPhone: null // 商家联系电话
                    }
                },
                roleRange: [{
                        id: "10",
                        name: "商家"
                    },
                    {
                        id: "7",
                        name: "大组长"
                    },
                    {
                        id: "8",
                        name: "小组长"
                    },
                    {
                        id: "9",
                        name: "工人"
                    }
                ],
            };
        },
        computed: {

        },
        methods: {
            pageBack() {
                uni.reLaunch({
                    url: '/pages/public/login'
                })
            },
            nextStep() {
                // 根据 currentStep 的不同，执行不同的验证逻辑
                if (this.currentStep === 1) {
                    // 验证步骤1：角色选择
                    if (!this.registerParams.roleId) {
                        this.$refs.notify.error("请选择一个角色");
                        return;
                    }
                } else if (this.currentStep === 2) {
                    // 验证步骤2：基础信息
                    if (!this.registerParams.userName) {
                        this.$refs.notify.error("请输入真实姓名");
                        return;
                    }
                    if (!this.registerParams.phone || !/^1[3-9]\d{9}$/.test(this.registerParams.phone)) {
                        this.$refs.notify.error("请输入正确的电话号码");
                        return;
                    }
                    if (this.registerParams.roleId === '10') {
                        this.registerParams.shopInfo.shopPhone = this.registerParams.phone;
                        this.registerParams.shopInfo.shopOwner = this.registerParams.userName;
                    }
                } else if (this.currentStep === 3) {
                    // 验证步骤3：其他基本信息
                    if (!this.registerParams.nickName) {
                        this.$refs.notify.error("请输入昵称");
                        return;
                    }
                } else if (this.currentStep === 4) {
                    // 验证步骤4：其他信息（根据角色选择的额外信息）
                    if (this.registerParams.roleId === '10') {
                        // 商家信息验证
                        if (!this.registerParams.shopInfo.shopName) {
                            this.$refs.notify.error("请输入商家名称");
                            return;
                        }
                        if (!this.registerParams.shopInfo.areaNum) {
                            this.$refs.notify.error("请输入区号");
                            return;
                        }
                        if (!this.registerParams.shopInfo.stallNum) {
                            this.$refs.notify.error("请输入门牌号");
                            return;
                        }
                        if (!this.registerParams.shopInfo.shopOwner) {
                            this.$refs.notify.error("请输入店长名");
                            return;
                        }
                        if (!this.registerParams.shopInfo.shopPhone || !/^1[3-9]\d{9}$/.test(this.registerParams
                                .shopInfo.shopPhone)) {
                            this.$refs.notify.error("请输入正确的商家联系电话");
                            return;
                        }
                    } else if (this.registerParams.roleId === '8' || this.registerParams.roleId === '9') {
                        if (!this.registerParams.groupId) {
                            this.$refs.notify.error("请选择分组");
                            return;
                        }
                    }

                    // 验证协议是否勾选
                    if (!this.agreement) {
                        this.$refs.notify.error("请阅读并同意下方协议");
                        return;
                    }

                    this.register();
                    return;
                }

                // 如果所有验证通过，进入下一步
                this.currentStep++;
            },
            prevStep() {
                this.currentStep--;
            },
            onRoleChange(roleId) {
                this.registerParams.roleId = roleId; // 将索引转化为实际角色id
                if (roleId != 10) {
                    this.registerParams.shopInfo = null;
                }
                this.nextStep();
            },
            selectGender(gender) {
                this.registerParams.gender = gender;
            },
            selectGroup(groupId) {
                this.registerParams.groupId = groupId;
            },
            async onChooseavatar(res) {
                this.registerParams.icon = res.detail.avatarUrl;
                const {
                    data,
                    code
                } = await imageApi.upload(this.registerParams.icon);
                if (code == 200) {
                    this.registerParams.icon = data;
                }
            },
            register() {
                try {
                    uni.showLoading();
                    uni.requestSubscribeMessage({
                        tmplIds: ['80r1vE7SGrwM2YmvbhlYT7EANwEp7LdlRzIcCqQksmQ'],
                        success: async(res) => {
                            let loginRes = await uni.login();
                            this.registerParams.wxCode = loginRes[1].code;
                            const {
                                code,
                                data
                            } = await authApi.register(this.registerParams);
                            if (code !== 200) return;
                            this.$refs.notify.success("注册成功");
                            setTimeout(() => {
                                uni.reLaunch({
                                    url: "/pages/public/login"
                                });
                            }, 1000);
                        },
                        fail(res) {
                            this.$refs.notify.error("请同意接受通知");
                            return
                        },
                        complete(res) {
                            console.log(res);
                        }
                    });

                } finally {
                    uni.hideLoading();
                }
            },
            async fetchGroups() {
                try {
                    uni.showLoading({
                        title: "请稍后"
                    })
                    const {
                        code,
                        data
                    } = await groupApi.getGroupByWx();
                    if (code == 200) {
                        this.allGroup = data;
                    }
                } finally {
                    uni.hideLoading();
                }

            },
            onGenderChange(e) {
                this.registerParams.gender = parseInt(e.detail.value);
            }
        },
        onReady() {

        },
        mounted() {
            this.fetchGroups();
        }
    };
</script>


<style lang="scss">
    .container {
        padding-top: 10vh;
        position: relative;
        width: 100vw;
        height: 100vh;
        overflow: hidden;
        background: #fff;
    }

    .picker {
        padding: 10px 0;
        border-bottom: 1px solid #ccc;
    }

    .back {
        background-color: #989898;
    }

    .next {
        background-color: #FA436A;
    }

    .disabled {
        background-color: #eca6b5;
    }


    .wrapper {
        position: relative;
        z-index: 90;
        padding-bottom: 40upx;
    }

    .back-btn {
        position: absolute;
        left: 40upx;
        z-index: 9999;
        padding-top: var(--status-bar-height);
        top: 40upx;
        font-size: 40upx;
        color: $font-color-dark;
    }

    .left-top-sign {
        font-size: 120upx;
        color: $page-color-base;
        position: relative;
        left: -16upx;
    }

    .right-top-sign {
        position: absolute;
        top: 80upx;
        right: -30upx;
        z-index: 95;

        &:before,
        &:after {
            display: block;
            content: "";
            width: 400upx;
            height: 80upx;
            background: #b4f3e2;
        }

        &:before {
            transform: rotate(50deg);
            border-radius: 0 50px 0 0;
        }

        &:after {
            position: absolute;
            right: -198upx;
            top: 0;
            transform: rotate(-50deg);
            border-radius: 50px 0 0 0;
            /* background: pink; */
        }
    }

    .left-bottom-sign {
        position: absolute;
        left: -270upx;
        bottom: -320upx;
        border: 100upx solid #d0d1fd;
        border-radius: 50%;
        padding: 180upx;
    }

    .welcome {
        position: relative;
        left: 50upx;
        top: -90upx;
        font-size: 46upx;
        color: #555;
        text-shadow: 1px 0px 1px rgba(0, 0, 0, .3);
    }

    .input-content {
        margin-top: 20px;
    }

    .input-item {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: center;
        padding: 0 30upx;
        background: $page-color-light;
        height: 120upx;
        border-radius: 4px;
        margin-bottom: 25rpx;

        &:last-child {
            margin-bottom: 0;
        }

        .tit {
            height: 50upx;
            line-height: 56upx;
            font-size: $font-sm+2upx;
            color: $font-color-base;
        }

        .avaterBtn {
            height: 75px;
            width: 75px;
            padding: 0;
        }

        image {

            height: 150rpx;
            width: 150rpx;
        }

        input {
            height: 60upx;
            font-size: $font-base + 2upx;
            color: $font-color-dark;
            width: 100%;
        }
    }

    .input-item-row {
        display: flex;
        flex-direction: row;
        gap: 10rpx;

        .input-item-2 {
            width: 50%;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            justify-content: center;
            padding: 0 30upx;
            background: $page-color-light;
            height: 120upx;
            border-radius: 4px;
            margin-bottom: 25rpx;
        }

        &:last-child {
            margin-bottom: 0;
        }

        .tit {
            height: 50upx;
            line-height: 56upx;
            font-size: $font-sm+2upx;
            color: $font-color-base;
        }

        input {
            height: 60upx;
            font-size: $font-base + 2upx;
            color: $font-color-dark;
            width: 100%;
        }
    }

    .roleBtns {
        button {
            margin-top: 20px !important;
            height: 133rpx !important;
            font-size: 23px !important;
            font-weight: 800 !important;
            border-radius: 14rpx !important;
            border-color: #ffbecc !important;
            color: #ff819c !important;
        }
    }

    .gender-buttons {
        width: 100%;
        display: flex;
        gap: 10px;
    }

    .gender-button {
        width: 45%;
        height: 55px;
        font-size: 21px;
        padding: 10px 20px;
        border-radius: 5px;
        background-color: transparent;
        cursor: pointer;
        transition: background-color 0.3s, color 0.3s;
    }

    .gender-button:nth-child(1).active {
        background-color: #439dfa;
        color: #fff;
    }

    .gender-button:nth-child(2).active {
        background-color: #ff708a;
        color: #fff;
    }


    .group-buttons {
        width: 100%;
        display: flex;
        gap: 10px;
        flex-direction: column;
    }

    .group-button {
        width: 100%;
        height: 55px;
        margin-bottom: 10px;
        display: flex;
        font-size: 21px;
        padding: 10px 20px;
        border-radius: 5px;
        background-color: transparent;
        cursor: pointer;
        transition: background-color 0.3s, color 0.3s;
        flex-direction: row;
        justify-content: space-between;
    }

    .group-button.active {
        background-color: #439dfa;
        color: #fff;
    }
</style>